<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<script>
// 递归树
function levels(dataArr, pid, level = 0) {
  const res = []
  dataArr.forEach(el => {
    if (el.pid === pid) {
      el.level = level
      const children = levels(dataArr, el.id, level + 1)
      if (children && children.length) {
        el.children = children
      }
      res.push(el)
    }
  })
  return res
}

// 扁平树
function trees(dataArr, pid, level = 0) {
  const res = []
  dataArr.forEach(el => {
    if (el.pid === pid) {
      el.level = level
      res.push(el)
      res.push(...trees(dataArr, el.id, level + 1))
    }
  })
  return res
}

// 扁平化
function plains(dataArr) {
  const res = []
  dataArr.forEach(el => {
    if (el.children && el.children.length) {
      res.push(...plains(el.children, res))
      delete el.children
    }
    res.push(el)
  })
  return res
}

// 递归父级
function parents(dataArr, id) {
  const res = []
  dataArr.forEach(el => {
    if (el.id === id) {
      res.push(el)
      res.push(...parents(dataArr, el.pid))
    }
  })
  return res
}

// 深度查找
function finds(dataArr, id) {
  let res = {}
  dataArr.forEach(el => {
    if (id === el.id) {
      res = el
    } else if (el.children && el.children.length) {
      res = finds(el.children, id)
    }
  })
  return res
}

// 深拷贝
function clones(target) {
  if (typeof target === 'object') {
    const cloneTarget = Array.isArray(target) ? [] : {}
    for (const key in target) {
      cloneTarget[key] = clones(target[key])
    }
    return cloneTarget
  } else {
    return target
  }
}

// 叶子节点
export function leafs (dataArr, children = 'children') {
  let res = []
  dataArr.forEach(el => {
    if (!el[children] || !el[children].length) {
      res.push(el)
    } else {
      res = leafs(el[children])
    }
  })
  return res
}

const list = [
    {id: 2, pid: 1, name: '2-1'},
    {id: 4, pid: 1, name: '4-2'},
    {id: 1, pid: 0, name: '1-0'},
    {id: 5, pid: 0, name: '5-0', function() {}},
    {id: 3, pid: 2, name: '3-2'}
]

</script>
</body>
</html>